﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LiJu
{
    /// <summary>
    /// 页面数据帮助类
    /// </summary>
    public static class PageDataDto
    {




        /// <summary>
        /// 构建三级菜单
        /// </summary>
        /// <param name="treeView"></param>
        /// <param name="menuItems"></param>
        public static void BuildThreeLevelMenu(TreeView treeView, List<SystemMenu> menuItems)
        {
            var allMenus = menuItems.ToDictionary(m => m.Id, m => m);


            treeView.CheckBoxes = true;

            TreeNode root = new TreeNode();
            root.Text = "主目录";
            root.Name = "A00";


            // 第一级菜单：直接添加到TreeView根节点
            foreach (var firstLevelMenu in menuItems.Where(m => m.ParentId == 1))
            {
                var treeNode = new TreeNode(firstLevelMenu.MenuName);
                //设置数据对象
                treeNode.Tag = firstLevelMenu;
                //设置选中状态
                treeNode.Checked = firstLevelMenu.IsChecked;
                //如果选中则进行菜单展开
                if (firstLevelMenu.IsChecked)
                {
                    treeNode.Expand();
                }

                // 第二级菜单：遍历第一级菜单的子项
                foreach (var secondLevelMenu in menuItems.Where(sm => sm.ParentId == firstLevelMenu.Id))
                {
                    var secondTreeNode = new TreeNode(secondLevelMenu.MenuName);
                    secondTreeNode.Tag = secondLevelMenu;
                    secondTreeNode.Checked = secondLevelMenu.IsChecked;
                    //如果选中则进行菜单展开
                    if (secondLevelMenu.IsChecked)
                    {
                        //选中需要打开上级菜单
                        treeNode.Expand();
                    }
                    treeNode.Nodes.Add(secondTreeNode);

                    // 第三级菜单：遍历第二级菜单的子项
                    foreach (var thirdLevelMenu in menuItems.Where(tm => tm.ParentId == secondLevelMenu.Id))
                    {
                        var thirdTreeNode = new TreeNode(thirdLevelMenu.MenuName);
                        thirdTreeNode.Tag = thirdLevelMenu;
                        thirdTreeNode.Checked = thirdLevelMenu.IsChecked;
                        //如果选中则进行菜单展开
                        if (thirdLevelMenu.IsChecked)
                        {
                            secondTreeNode.Expand();
                        }
                        secondTreeNode.Nodes.Add(thirdTreeNode);
                    }
                }
                //把一级菜单添加到根目录
                root.Nodes.Add(treeNode);
            }

            root.Expand();

            treeView.Nodes.Add(root);
        }

        /// <summary>
        /// 将DataTable 转换为list<类>集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="table"></param>
        /// <returns></returns>
        public static List<T> ConvertToListClass<T>(this DataTable table) where T : new()
        {
            var properties = typeof(T).GetProperties();
            var list = new List<T>();

            foreach (DataRow row in table.Rows)
            {
                var obj = new T();
                foreach (var prop in properties)
                {
                    if (row.Table.Columns.Contains(prop.Name))
                    {
                        var value = row[prop.Name];
                        if (value != DBNull.Value)
                        {
                            prop.SetValue(obj, Convert.ChangeType(value, prop.PropertyType), null);
                        }
                    }
                }
                list.Add(obj);
            }

            return list;
        }



        private static void TraverseAndCheckNodes(TreeNode node, List<int> selectedNodeIds)
        {
            // 检查当前节点ID是否在已选择的节点ID列表中
            if (selectedNodeIds.Contains((int)node.Tag)) // 假设TreeNode的Tag存储了节点的ID
            {
                node.Checked = true; // 设置节点的Checkbox为选中状态
            }
            else
            {
                node.Checked = false; // 或者保持未选中状态
            }

            // 遍历子节点
            foreach (TreeNode childNode in node.Nodes)
            {
                TraverseAndCheckNodes(childNode, selectedNodeIds);
            }
        }


        /// <summary>
        /// 添加系统日志记录
        /// </summary>
        /// <param name="model"></param>
        /// <param name="operateContent"></param>
        public static void SystemLogInfoAdd(string model, string operateContent)
        {
            //操作时间
            DateTime operateTime = DateTime.Now;
            //操作用户ID/Name
            string operateNo = ConfigurationManager.AppSettings["UserID"];
            string operateName = ConfigurationManager.AppSettings["UserName"];

            string sql = string.Format(@"INSERT INTO systemlog(OperateTime,OperateNo,OperateName,Model,OperateContent)
                                        VALUES('{0}','{1}','{2}','{3}','【{4}】')", operateTime, operateNo, operateName, model, operateContent);

            Db.DalMySQL.ExecuteNonQuery(sql);
        }


        /// <summary>
        /// 获取当前用户所拥有的角色菜单权限
        /// </summary>
        /// <returns></returns>
        public static SystemMenuRole SystemMenuRoleInfo()
        {
            //用户名
            string userID = ConfigurationManager.AppSettings["UserID"];
            if (!string.IsNullOrWhiteSpace(userID))
            {
                return SystemMenuRoleInfo(userID);
            }
            else
            {
                return null;
            }
        }

        public static SystemMenuRole SystemMenuRoleInfo(string userID)
        {
            string sql = string.Format(@"select a.userID,b.roleName,d.MenuNo from usermanager a
                                        join rolemanager b on a.userRole=b.Id  and b.state=1 
                                        join roleinmenu c on b.Id=c.roleID
                                        left join systemmenu d on c.menuID=d.id
                                        WHERE a.userID='{0}'", userID);

            //角色菜单列表
            var menuList = UserOpMysql.ExecuteDataTable(sql);

            SystemMenuRole menuRole = new SystemMenuRole();

            //进行赋值 用于判断页面是否拥有此功能元素
            if (menuList.Rows.Count > 0)
            {
                for (int i = 0; i < menuList.Rows.Count; i++)
                {
                    string menuNo = Convert.ToString(menuList.Rows[i]["MenuNo"]);

                    switch (menuNo)
                    {

                        case "Work":
                            menuRole.Work = true;
                            break;
                        case "Work_NG":
                            menuRole.Work_NG = true;
                            break;
                        case "Work_Test":
                            menuRole.Work_Test = true;
                            break;
                        case "Work_DianJian"://点检
                            menuRole.Work_DianJian = true;
                            break;
                        case "Work_SongDing"://重新送钉判定
                            menuRole.Work_SongDing = true;
                            break;
                        case "MESControl":
                            menuRole.MESControl = true;
                            break;
                        case "ProductView":
                            menuRole.ProductView = true;
                            break;
                        case "TestRecords":
                            menuRole.TestRecords = true;
                            break;
                        case "Passage":
                            menuRole.Passage = true;
                            break;
                        case "SetUp":
                            menuRole.SetUp = true;
                            break;
                        case "Setting":
                        case "SystemManager":
                            menuRole.SystemManager = true;
                            break;
                        case "ParameterManager":
                            menuRole.ParameterManager = true;
                            break;
                        case "UserManager":
                            menuRole.UserManager = true;
                            break;
                        case "RoleManager":
                            menuRole.RoleManager = true;
                            break;
                        case "Systemlog":
                            menuRole.Systemlog = true;
                            break;
                        case "User_Add":
                            menuRole.User_Add = true;
                            break;
                        case "User_Edit":
                            menuRole.User_Edit = true;
                            break;
                        case "User_Del":
                            menuRole.User_Del = true;
                            break;
                        case "Role_Add":
                            menuRole.Role_Add = true;
                            break;
                        case "Role_Edit":
                            menuRole.Role_Edit = true;
                            break;
                        case "Role_Del":
                            menuRole.Role_Del = true;
                            break;
                        case "Parm_Load":
                            menuRole.Parm_Load = true;
                            break;
                        case "Parm_Setting":
                            menuRole.Parm_Setting = true;
                            break;
                        case "Parm_Save":
                            menuRole.Parm_Save = true;
                            break;
                        case "Parm_Exec":
                            menuRole.Parm_Exec = true;
                            break;
                        case "Set_Cancel":
                            menuRole.Set_Cancel = true;
                            break;
                        case "Set_Save":
                            menuRole.Set_Save = true;
                            break;
                        case "Product_Add":
                            menuRole.Product_Add = true;
                            break;
                        case "Product_Edit":
                            menuRole.Product_Edit = true;
                            break;
                        case "Product_Check":
                            menuRole.Product_Check = true;
                            break;
                        case "Product_State":
                            menuRole.Product_State = true;
                            break;
                        case "Product_Del":
                            menuRole.Product_Del = true;
                            break;
                    }
                }

            }
            return menuRole;
        }

        /// <summary>
        /// 返回当前用户所拥有的一级菜单
        /// </summary>
        /// <param name="userID"></param>
        /// <returns></returns>
        public static UserInfoResultDto SystemParentMenuRoleInfo(string userID, string password)
        {
            string sql = string.Format(@"SELECT a.*,(select count(*) from roleinmenu b left join systemmenu c 
                                                on b.menuID=c.Id where b.roleID=a.userRole and c.MenuType='菜单') as 'roleCount',
                                                a1.state as 'roleState' from usermanager a
                                                left join rolemanager a1 on a.userRole=a1.Id
                                                WHERE (a.UserID='{0}' or a.UserName='{0}') and a.`Password`='{1}' ", userID, password);

            List<UserInfoResultDto> userInfoResultDtos = new List<UserInfoResultDto>();

            //执行sql，验证密码等数据是否正常
            var result = UserOpMysql.ExecuteDataTable(sql);
            if (result.Rows.Count > 0)
            {
                userInfoResultDtos = result.ConvertToListClass<UserInfoResultDto>();
                return userInfoResultDtos[0];
            }
            else
            {
                return new UserInfoResultDto() { Id = 0 };
            }


        }
    }

    /// <summary>
    /// 登录用户数据
    /// </summary>
    public class UserInfoResultDto
    {
        /// <summary>
        /// 主键ID
        /// </summary>
        public int Id { get; set; }

        /// <summary>
        /// 用户编号
        /// </summary>
        public string UserID { get; set; }

        /// <summary>
        /// 用户名称
        /// </summary>
        public string UserName { get; set; }

        /// <summary>
        /// 用户密码
        /// </summary>
        public string PassWord { get; set; }

        /// <summary>
        /// 用户状态
        /// </summary>
        public bool State { get; set; }

        /// <summary>
        /// 角色数量
        /// </summary>
        public int RoleCount { get; set; }

        /// <summary>
        /// 角色状态
        /// </summary>
        public bool RoleState { get; set; }



    }



    /// <summary>
    /// 系统菜单
    /// </summary>
    public class SystemMenu
    {
        /// <summary>
        /// ID
        /// </summary>
        public int Id { get; set; }


        /// <summary>
        /// 菜单编号
        /// </summary>
        public string MenuNo { get; set; }

        /// <summary>
        /// 菜单名称
        /// </summary>
        public string MenuName { get; set; }

        /// <summary>
        /// 父级菜单
        /// </summary>
        public int ParentId { get; set; }

        /// <summary>
        /// 选中状态
        /// </summary>
        public bool IsChecked { get; set; }
    }

    /// <summary>
    /// 切换用户时返回数据
    /// </summary>
    public class SwitchUserInfo
    {
        public string UserID { get; set; }

        public string UserName { get; set; }
    }


    /// <summary>
    ///角色所拥有菜单详情类
    /// </summary>
    public class SystemMenuRole
    {
        /// <summary>
        /// 工作台
        /// </summary>
        public bool Work { get; set; }

        /// <summary>
        /// NG判定
        /// </summary>
        public bool Work_NG { get; set; }
        
        /// <summary>
        /// 测试模式
        /// </summary>
        public bool Work_Test { get; set; }

        /// <summary>
        /// 点检
        /// </summary>
        public bool Work_DianJian { get; set; }

        /// <summary>
        /// 重新送钉判定
        /// </summary>
        public bool Work_SongDing { get; set; }    
        

        /// <summary>
        /// MES控制面板
        /// </summary>
        public bool MESControl { get; set; }


        /// <summary>
        /// 产品
        /// </summary>
        public bool ProductView { get; set; }

        /// <summary>
        /// 记录
        /// </summary>
        public bool TestRecords { get; set; }

        /// <summary>
        /// 曲线
        /// </summary>
        public bool Passage { get; set; }

        /// <summary>
        /// 设置
        /// </summary>
        public bool SetUp { get; set; }


        

        /// <summary>
        /// 系统
        /// </summary>
        public bool SystemManager { get; set; }

        /// <summary>
        /// 参数
        /// </summary>
        public bool ParameterManager { get; set; }


        /// <summary>
        /// 系统参数-取消
        /// </summary>
        public bool Set_Cancel { get; set; }

        /// <summary>
        /// 系统参数-保存
        /// </summary>
        public bool Set_Save { get; set; }



        /// <summary>
        /// 用户管理
        /// </summary>
        public bool UserManager { get; set; }

        /// <summary>
        /// 角色管理
        /// </summary>
        public bool RoleManager { get; set; }

        /// <summary>
        /// 系统日志
        /// </summary>
        public bool Systemlog { get; set; }

        /// <summary>
        /// 用户管理 -添加
        /// </summary>
        public bool User_Add { get; set; }

        /// <summary>
        /// 用户管理-修改
        /// </summary>
        public bool User_Edit { get; set; }

        /// <summary>
        /// 用户管理-删除
        /// </summary>
        public bool User_Del { get; set; }

        /// <summary>
        /// 角色管理-删除
        /// </summary>
        public bool Role_Del { get; set; }

        /// <summary>
        /// 角色管理-添加
        /// </summary>
        public bool Role_Add { get; set; }

        /// <summary>
        /// 角色管理-修改
        /// </summary>
        public bool Role_Edit { get; set; }

        /// <summary>
        /// 参数-加载
        /// </summary>
        public bool Parm_Load { get; set; }

        /// <summary>
        /// 参数-参数设置
        /// </summary>
        public bool Parm_Setting { get; set; }

        /// <summary>
        /// 参数-保存
        /// </summary>
        public bool Parm_Save { get; set; }

        /// <summary>
        /// 参数-执行
        /// </summary>
        public bool Parm_Exec { get; set; }

        /// <summary>
        /// 产品-添加
        /// </summary>
        public bool Product_Add { get; set; }

        /// <summary>
        /// 产品-编辑
        /// </summary>
        public bool Product_Edit { get; set; }

        /// <summary>
        /// 产品-详情
        /// </summary>
        public bool Product_Check { get; set; }

        /// <summary>
        /// 产品-状态
        /// </summary>
        public bool Product_State { get; set; }

        /// <summary>
        /// 产品-删除
        /// </summary>
        public bool Product_Del { get; set; }
    }


    /// <summary>
    /// 设置页面旧值
    /// </summary>
    public class SettingOldValue
    {
        /// <summary>
        /// 
        /// </summary>
        public string OldValue1 { get; set; }
        public string OldValue2 { get; set; }
        public string OldValue3 { get; set; }
        public string OldValue4 { get; set; }
        public string OldValue5 { get; set; }
        public string OldValue6 { get; set; }
        public string OldValue7 { get; set; }
        public string OldValue8 { get; set; }
        public string OldValue91 { get; set; }
        public string OldValue10 { get; set; }
        public string OldValue11 { get; set; }
        public string OldValue12 { get; set; }
    }
}
